#-*-coding:utf-8-*-

def joke():
    try:
        for i in random.sample(range(335), 1):
            page = 'page=' + str(i)
            full_url = 'http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?' + page
            req = urllib2.Request(full_url)
            req.add_header("apikey", "自己的key")
            resp = urllib2.urlopen(req, timeout=5)
            data = json.loads(resp.read())
            for i in random.sample(range(len(data['showapi_res_body']['contentlist'])), 1):
                return data['showapi_res_body']['contentlist'][i]['title'] + '\\n' + data['showapi_res_body']['contentlist'][i]['text'] + '\\n'
    except Exception:
        return '抱歉，你运气不好，没有人愿意给你讲笑话，请重试。'


def weather(city_name):
    str_city = 'city=' + str(city_name)
    url = 'http://apis.baidu.com/heweather/weather/free?' + str_city
    req = urllib2.Request(url)
    req.add_header("apikey", "自己的key")
    resp = urllib2.urlopen(req)
    content = resp.read().decode('utf-8')
    city = re.findall(r'"city":"(.*?)"', content, re.S)
    update = re.findall(r'"loc":"(.*?)"', content, re.S)
    txt = re.findall(r'"txt_d":"(.*?)"', content, re.S)
    max_t = re.findall(r'"max":"(.*?)"', content, re.S)
    min_t = re.findall(r'"min":"(.*?)"', content, re.S)
    hum = re.findall(r'"hum":"(.*?)"', content, re.S)
    pcpn = re.findall(r'"pcpn":"(.*?)"', content, re.S)
    vis = re.findall(r'"vis":"(.*?)"', content, re.S)
    wind_dir = re.findall(r'"dir":"(.*?)"', content, re.S)
    wind_sc = re.findall(r'"sc":"(.*?)"', content, re.S)
    wind_spd = re.findall(r'"spd":"(.*?)"', content, re.S)
    return '城市：' + city[0] + '\\n' + '更新时间：' + update[0] + '\\n' + '天气情况：' + txt[0] + '\\n' + '最高温度：' + max_t[0] + '度' + '\\n' + '最低温度：' + min_t[0] + '度' + '\\n' + '相对湿度：' + hum[0] + '%' + '\\n' + '降水量：' + pcpn[0] + 'mm' + '\\n' + '能见度：' + vis[0] + 'km' + '\\n' + '风向：' + wind_dir[0] + '\\n' + '风力：' + wind_sc[0] + '\\n' + '风速：' + wind_spd[0] + 'km/h' + '\\n'
